package com.mb.app.appused.tools;

import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;

public class TaskEvent {

	List<TaskItem> eventQueue = new ArrayList<TaskItem>();;
	public TaskEvent() {
	}

	public void addEvent(TaskItem item) {
		if (eventQueue.contains(item))
			return;
		eventQueue.add(item);
		if (eventQueue.size() == 1) {
			RunTask task = new RunTask(this, eventQueue.get(0));
			task.execute();
		}
	}

	void checkExcute(TaskItem item) {
		if (eventQueue.contains(item))
			eventQueue.remove(item);
		if (eventQueue.size() > 0) {
			RunTask task = new RunTask(this, eventQueue.get(0));
			task.execute();
		}
	}

	class RunTask extends AsyncTask<Void, Integer, Void> {
		TaskItem item;
		TaskEvent taskEvent;

		public RunTask(TaskEvent myEvent, TaskItem item) {
			this.item = item;
			this.taskEvent = myEvent;
		}

		// onPreExecute方法用于在执行后台任务前做一些UI操作
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			if (item != null && item.task != null)
				item.task.onStart();
		}

		// doInBackground方法内部执行后台任务,不可在此方法内修改UI
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			if (item != null && item.task != null)
				item.task.onExcute();
			return null;
		}

		// onPostExecute方法用于在执行完后台任务后更新UI,显示结果
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (item != null && item.task != null)
				item.task.onDestroy();
			taskEvent.checkExcute(item);
		}

		// onProgressUpdate方法用于更新进度信息
		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			if (item != null && item.task != null)
				item.task.onUpdata(values[0]);
		}

	}

	/**
	 * 类定义
	 * 
	 * @author 若远帆
	 * 
	 */
	public class TaskItem {
		
		public String name;
		public ITaskItem task;
		public TaskItem(String name,ITaskItem task){
			this.name=name;
			this.task=task;
		}
	}

	/**
	 * 接口定义
	 * 
	 * @author 若远帆
	 * 
	 */
	public interface ITaskItem {
		public void onStart();

		public void onExcute();

		public void onUpdata(int p);

		public void onDestroy();
	}

}
